package com.demo.controller;

import com.demo.service.IDemoService;
import com.spring.framework.annotation.MyAutowired;
import com.spring.framework.annotation.MyController;
import com.spring.framework.annotation.MyRequestMapping;
import com.spring.framework.annotation.MyRequestParam;
import com.spring.framework.webmvc.servlet.MyModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ππ
 * @date 2020-11-16 10:32
 * @desc 声明controller
 */
@MyRequestMapping(value = "/demo")
@MyController
public class DemoController {
    @MyAutowired
    private IDemoService demoService;

    @MyRequestMapping(value = "/query")
    public MyModelAndView query(HttpServletRequest request, HttpServletResponse response, @MyRequestParam("name") String name) {
        String msg = demoService.queryByName(name);
        try {
            return out(response,msg);
        } catch (Throwable e) {
            e.printStackTrace();
            Map<String,String> model = new HashMap<String,String>();
            model.put("detail",e.getCause().getMessage());
            model.put("stackTrace", Arrays.toString(e.getStackTrace()));
            return new MyModelAndView("500",model);
        }
    }
    @MyRequestMapping(value = "/add*.json")
    public MyModelAndView add(HttpServletRequest request,HttpServletResponse response,
                              @MyRequestParam("name") String name,@MyRequestParam("addr") String addr){
        try {
            String result = demoService.add(name);
            return out(response,result);
        }catch (Throwable e){
            Map<String,String> model = new HashMap<String,String>();
            model.put("detail",e.getCause().getMessage());
            model.put("stackTrace", Arrays.toString(e.getStackTrace()));
            return new MyModelAndView("500",model);
        }
    }
    private MyModelAndView out(HttpServletResponse resp,String str){
        try {
            resp.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
